package com.jiehoo.ooqi;

import java.io.Serializable;

/**
 * Query field, used in select, condition, sort, having and sort part of QL.
 */
public class Field implements Serializable {
  private static final long serialVersionUID = 6332383907050641747L;

  /**
   * From target of field.
   */
  private From from;

  /**
   * Field name.
   */
  private String name;

  /**
   * Aggregation function.
   */
  private Function function;

  /**
   * Filed alias, especially needed when Function is not null.
   */
  private String alias;

  public Field() {
  }

  public Field(String name) {
    this.name = name;
  }

  public Field(From from, String name) {
    this.name = name;
    this.from = from;
  }

  public Field(String name, Function function) {
    this.name = name;
    this.function = function;
  }

  public Field(String name, Function function, String alias) {
    this.name = name;
    this.function = function;
    this.alias = alias;
  }

  public Field(From from, String name, Function function) {
    this.from = from;
    this.name = name;
    this.function = function;
  }

  public From getFrom() {
    return from;
  }

  public void setFrom(From from) {
    this.from = from;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public Function getFunction() {
    return function;
  }

  public void setFunction(Function function) {
    this.function = function;
  }

  public String getAlias() {
    return alias;
  }

  public void setAlias(String alias) {
    this.alias = alias;
  }

  /**
   * Field name only, does not include function and alias part.
   */
  public String getFieldName() {
    StringBuilder buffer = new StringBuilder();
    if (from != null) {
      String alias = from.getAliasOnly();
      if (alias != null && alias.length() > 0) {
        buffer.append(alias).append(".");
      }
    }
    buffer.append(name);
    return buffer.toString();
  }

  public String toString() {
    StringBuilder buffer = new StringBuilder();
    if (function != null) {
      buffer.append(function).append("(");
    }
    buffer.append(getFieldName());
    if (function != null) {
      buffer.append(")");
    }
    if (alias != null && alias.length() > 0) {
      buffer.append(" as ").append(alias);
    }
    return buffer.toString();
  }
}
